﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Gdmec.Load
{
    //加载任务
    public class LoadTask
    {
        public string name;
        public readonly List<string> paths = new List<string>();
        private readonly Queue<LoadParam> load_params = new Queue<LoadParam>();
        public Action onFinish;
        public LoadTaskDelegate onFinish_all;
        protected int finish_count = 0;
        public bool IsFinish { get { return finish_count >= paths.Count; } }
        public int Count { get { return load_params.Count; } }
        public object LastObj { get; private set; }

        public LoadParam GetParam { get { return load_params.Dequeue(); } }

        public void Init()
        {
            load_params.Clear();
            foreach (var path in paths)
            {
                if (string.IsNullOrEmpty(path.Trim()))
                {
                    //if (template.is_debug) Debug.LogError("LoadTask null path !!");
                    continue;
                }
                LoadParam param = new LoadParam();
                param.group = name;
                param.path = path;
                load_params.Enqueue(param);
            }
        }

        public void UnInit()
        {
           // if (template.is_debug) Debug.LogFormat("Time : {0} UnInitTask :{1} count:", Time.time, name, paths.Count);
            name = string.Empty;
            paths.Clear();
            load_params.Clear();
            onFinish = null;
            onFinish_all = null;
            LastObj = null;
            finish_count = 0;
        }

        public void TryFinish(LoadWorker worker) 
        {
            if (name == worker.param.group) 
            {
                finish_count++;
                LastObj = worker.obj;
            }   
        }

        public void TryFinish(LoadParam param)
        {
            if (name == param.group)
            {
                finish_count++;
            }
        }

        public void Finish()
        {
            if (!IsFinish) return;
            onFinish?.Invoke();
            onFinish_all?.Invoke(this);
            UnInit();
        }

    }
}
